package com.gopay.bis.service.bank.impl.ebank;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.ebank.PayEaseManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.PayEaseConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.payease.ebank.PayEaseMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 首信易支付service实现
 * 
 * @PayEaseBankServiceImpl.java
 * @author zhengxue
 * @2015-9-7 下午3:55:09 www.gopay.com.cn Inc.All rights reserved.
 */
public class PayEaseBankServiceImpl implements BankInteractRemoteService {
    @Resource(name = "payEaseManager")
    PayEaseManager payEaseManager;

    @Override
    public Result pay(BaseMessage base) {
        Result result = new Result(false);
        try {
            BigDecimal amt = new BigDecimal(1500);
            if (base.getAmount().compareTo(amt) == -1) {
                // 金额小于1500走小额商户号
                base.setSmallMer(true);
            }
            PayEaseMessage message = (PayEaseMessage) payEaseManager.sign(base);
            result.setDefaultModel(message);
            result.setSuccess(true);
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6029);
        }
        return result;

    }

    @Override
    public Result bankBack(BaseMessage base) {
        Result result = new Result(false);
        PayEaseMessage message = new PayEaseMessage();
        BeanUtils.copyProperties(base, message);
        try {
            boolean flag = (Boolean) payEaseManager.verify(message);
            result.setModel("message", message);
            result.setDefaultModel(flag);
            result.setSuccess(true);

            if (result != null && result.isSuccess() && (Boolean) result.getDefaultModel()) {
                Map<String, String> param = new HashMap<String, String>();
                if (message.getVpstatus() != null && message.getVpstatus().equals(PayEaseConstants.TRAN_STATE_SUCCESS)) {
                    // 如果该订单成功通知后台地址入账
                    param.put("orderId", base.getOrderId());
                    param.put("amt", message.getVamount());
                    param.put("cardType", "Unknown");
                    param.put("notifyNum", "1");
                    param.put("payStatus", "00");
                    param.put("retCode", "00");
                    param.put("retMsg", "");
                    param.put("signData", message.getSignMessage());
                    param.put("isFront", base.isFront() + "");
                    result.setModel("isNotifyCashier", param);
                    result.setOrderStatus(true);
                } else {
                    // 通知后台地址该订单失败
                    param.put("orderId", base.getOrderId());
                    param.put("amt", message.getVamount());
                    param.put("cardType", "Unknown");
                    param.put("notifyNum", "1");
                    param.put("payStatus", "01");
                    param.put("retCode", "01");
                    param.put("retMsg", "");
                    param.put("signData", message.getSignMessage());
                    param.put("isFront", base.isFront() + "");
                    result.setModel("isNotifyCashier", param);
                    result.setOrderStatus(false);
                }
            }
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
        }
        return result;
    }

    @Override
    public Result query(BaseMessage base) {
    	Result result = new Result(false);
		
    	PayEaseMessage messageB2C = new PayEaseMessage();
		BeanUtils.copyProperties(base, messageB2C);
		try {
			PayEaseMessage repMessage = (PayEaseMessage) payEaseManager.query(messageB2C);
			result.setDefaultModel(repMessage);
			result.setSuccess(true);
			if(BisPayCheckUtils.checkExternalOrderID(messageB2C.getOrderId())){
				Map<String, String> param = new HashMap<String, String>();
				param.put("orderId", messageB2C.getOrderId());
				param.put("amount", messageB2C.getAmount().toString());
				if (repMessage == null) {
					// 查询订单为空
					param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
					param.put("returnMessage", "银行返回对账结果为空");
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
				}
				String orderStatus =repMessage.getVorderstatus(); // 交易状态
				//成功处理
				if (orderStatus.equals(PayEaseConstants.QUERY_VPSTATUS_SUCCESS)) {
					param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
					param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
					param.put("returnMessage", "交易成功");
				}
				//支付结果不确定
				else if (Arrays.asList(PayEaseConstants.QUERY_VPSTATUS_UNCERTAINTY.split(",")).contains(orderStatus)){
					param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
					param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					param.put("returnMessage", "银行返回交易待确认");
				}
				else {
					param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
					param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
					param.put("returnMessage", "交易失败");
				}
				result.setModel("queryResult", param);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6032);
		}
        return result;
    }

    @Override
    public Result dayend(BaseMessage arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result queryBack(BaseMessage arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refund(BaseMessage arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refundBack(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refundQuery(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

	@Override
	public Result sendBankRefund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

}
